<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '我的',
  },
}
</route>

<script setup lang="ts">
import type { ProfileInfoRespVO, UserStatsOverviewRespVO } from '@/types/profile'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getUserProfile, getUserStatsOverview, handleProfileError, processAvatarUrl } from '@/api/profile'
import { deleteUserAccount } from '@/api/userActions'
import { useUserStore } from '@/store/user'
import { checkLoginStatus } from '@/utils/auth'

// 用户store
const userStore = useUserStore()

// 用户信息
const userInfo = ref<ProfileInfoRespVO | null>(null)
const userStats = ref<UserStatsOverviewRespVO | null>(null)
const loading = ref(false)
const error = ref('')

// 密码输入弹窗相关
const showPasswordModal = ref(false)
const passwordInput = ref('')

// console.log(userInfo.value);

// 统一菜单列表
const allMenuItems = ref([
  { id: 1, title: '我的收藏', icon: 'heart', iconType: 'uni', color: '#ff6b6b', type: 'navigate', path: '/pages-sub/profile/my-favorites/index' },
  { id: 2, title: '阅读记录', icon: 'calendar', iconType: 'uni', color: '#4ecdc4', type: 'navigate', path: '/pages-sub/profile/reading-history/index' },
  { id: 3, title: '回收站', icon: 'trash', iconType: 'uni', color: '#607d8b', type: 'navigate', path: '/pages-sub/profile/trash/index' },
  { id: 4, title: '个人资料', icon: 'person', iconType: 'uni', color: '#45b7d1', type: 'navigate', path: '/pages-sub/profile/profile-edit/index' },
  { id: 5, title: '账号注销', icon: 'gear', iconType: 'uni', color: '#4a90e2', type: 'action', action: 'settings' },
  { id: 6, title: '退出登录', icon: 'logout', iconType: 'wd', color: '#ff5252', type: 'action', action: 'logout' },
])

// 加载用户信息
async function loadUserInfo() {
  try {
    loading.value = true
    error.value = ''

    const [profileRes, statsRes] = await Promise.all([
      getUserProfile(),
      getUserStatsOverview(),
    ])

    // console.log('Profile response:', profileRes)
    // console.log('Stats response:', statsRes)

    // HTTP工具类返回的是 IResData<T>，所以需要访问 .data
    if (profileRes && profileRes.data) {
      userInfo.value = profileRes.data
      // console.log('User info set:', userInfo.value)
    }

    if (statsRes && statsRes.data) {
      userStats.value = statsRes.data
      // console.log('User stats set:', userStats.value)
    }
  }
  catch (err: any) {
    console.error('加载用户信息失败:', err)

    // 检查是否是401错误（已经在拦截器中处理跳转）
    if (err?.data?.code === 401 || err?.statusCode === 401) {
      console.log('401错误已处理，用户将跳转到登录页面')
      return // 不显示错误提示，让拦截器处理跳转
    }

    // 其他错误才显示错误提示
    error.value = handleProfileError(err)
    uni.showToast({
      title: error.value,
      icon: 'none',
      duration: 2000,
    })
  }
  finally {
    loading.value = false
  }
}

// 刷新数据
async function refreshData() {
  await loadUserInfo()
}

// 统一菜单点击处理
function handleMenuClick(item: any) {
  if (item.type === 'navigate') {
    // 导航类型，跳转到指定页面
    uni.navigateTo({
      url: item.path,
    })
  }
  else if (item.type === 'action') {
    // 操作类型，执行对应操作
    handleAction(item.action)
  }
}

// 处理密码确认
async function handlePasswordConfirm() {
  if (!passwordInput.value.trim()) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none',
    })
    return
  }

  try {
    console.log('开始注销账号，密码长度:', passwordInput.value.length)

    // 隐藏密码弹窗
    showPasswordModal.value = false

    // 显示注销中提示
    uni.showLoading({
      title: '注销中...',
    })

    // 调用后端注销账号API
    console.log('调用deleteUserAccount API...')
    const result = await deleteUserAccount({
      password: passwordInput.value,
      reason: '用户主动注销',
    })
    console.log('账号注销结果:', result)

    // 清除本地用户数据
    await userStore.logout()
    userInfo.value = null
    userStats.value = null

    uni.hideLoading()

    // 显示注销成功提示
    uni.showToast({
      title: '账号已注销',
      icon: 'success',
    })

    // 跳转到登录页
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/login/index' })
    }, 1000)
  }
  catch (error: any) {
    uni.hideLoading()
    console.error('账号注销失败:', error)
    console.error('错误详情:', {
      message: error?.message,
      data: error?.data,
      response: error?.response,
      status: error?.status,
      statusText: error?.statusText,
    })

    // 显示错误提示
    let errorMsg = '注销失败，请重试'
    if (error?.data?.msg) {
      errorMsg = error.data.msg
    }
    else if (error?.response?.data?.msg) {
      errorMsg = error.response.data.msg
    }
    else if (error?.message) {
      errorMsg = error.message
    }

    uni.showToast({
      title: errorMsg,
      icon: 'none',
      duration: 3000,
    })
  }

  // 清空密码输入
  passwordInput.value = ''
}

// 取消密码输入
function handlePasswordCancel() {
  showPasswordModal.value = false
  passwordInput.value = ''
}

// 处理操作类型的点击
function handleAction(action: string) {
  switch (action) {
    case 'settings':
      // 账号注销确认
      uni.showModal({
        title: '账号注销',
        content: '注销账号将永久删除您的所有数据，此操作不可恢复，确定要注销吗？',
        confirmText: '确定注销',
        cancelText: '取消',
        success: async (res) => {
          if (res.confirm) {
            // 显示密码输入弹窗
            showPasswordModal.value = true
          }
        },
      })
      break
    case 'logout':
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 显示退出中提示
              uni.showLoading({
                title: '退出中...',
              })

              // 调用用户store的logout方法，真正退出登录
              await userStore.logout()

              // 清除页面本地数据
              userInfo.value = null
              userStats.value = null

              uni.hideLoading()

              // 显示退出成功提示
              uni.showToast({
                title: '已退出登录',
                icon: 'success',
              })

              // 跳转到登录页
              setTimeout(() => {
                uni.reLaunch({ url: '/pages/login/index' })
              }, 1000)
            }
            catch (error) {
              uni.hideLoading()
              console.error('退出登录失败:', error)

              // 即使API调用失败，也要清除本地状态
              await userStore.logout()
              userInfo.value = null
              userStats.value = null

              uni.showToast({
                title: '已退出登录',
                icon: 'success',
              })

              setTimeout(() => {
                uni.reLaunch({ url: '/pages/login/index' })
              }, 1000)
            }
          }
        },
      })
      break
    // case 'time':
    //   uni.showToast({
    //     title: '工作时间：9:00-21:00',
    //     icon: 'none'
    //   })
    //   break
  }
}

// 获取用户头像
function getUserAvatar() {
  if (userInfo.value?.avatar) {
    return processAvatarUrl(userInfo.value.avatar)
  }
  // 使用默认头像（base64编码的简单头像图标）
  return ''
}

// 获取用户昵称
function getUserNickname() {
  return userInfo.value?.nickname || userInfo.value?.username || '用户'
}

// 获取格式化的统计数据
// const getFormattedStats = () => {
//   if (!userStats.value) return null
//   return formatUserStats(userStats.value)
// }

onLoad(() => {
  console.log('我的页面加载完成')

  // 检查登录状态
  if (checkLoginStatus()) {
    loadUserInfo()
  }
})

// 页面显示时也检查登录状态
onShow(() => {
  console.log('我的页面显示')

  // 检查登录状态
  if (checkLoginStatus()) {
    // 如果已经有用户信息，可以选择刷新
    if (!userInfo.value) {
      loadUserInfo()
    }
  }
})

// 头像加载错误处理
function onAvatarError(event: any) {
  console.log('头像加载失败，使用默认头像')
  // 使用默认头像
  if (event.target) {
    event.target.src = '/static/images/default-avatar.png'
  }
}

// 页面显示时刷新数据
onShow(() => {
  refreshData()
})
</script>

<template>
  <view class="my-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading" content-text="{ contentText: { contentdown: '加载中...', contentrefresh: '加载中...', contentnomore: '加载中...' } }" />
    </view>

    <!-- 用户信息 -->
    <view v-else class="user-info">
      <view class="user-profile">
        <image
          class="user-avatar"
          :src="getUserAvatar()"
          mode="aspectFill"
          @error="onAvatarError"
        />
        <view class="user-details">
          <text class="user-name">
            {{ getUserNickname() }}
          </text>
        </view>
        <!-- 刷新按钮 -->
        <view class="refresh-btn" @click="refreshData">
          <uni-icons type="refresh" size="20" color="#fff" />
        </view>
      </view>

      <!-- 用户统计信息 -->
      <view v-if="userStats" class="user-stats">
        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-value">
              {{ userStats.totalReadBooks }}
            </text>
            <text class="stat-label">
              已读绘本
            </text>
          </view>
          <view class="stat-item">
            <text class="stat-value">
              {{ userStats.totalPunchDays }}
            </text>
            <text class="stat-label">
              打卡天数
            </text>
          </view>
          <view class="stat-item">
            <text class="stat-value">
              {{ userStats.currentStreak }}
            </text>
            <text class="stat-label">
              连续天数
            </text>
          </view>
          <view class="stat-item">
            <text class="stat-value">
              {{ userStats.totalFavorites }}
            </text>
            <text class="stat-label">
              收藏数量
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 统一菜单列表 -->
    <view class="menu-section">
      <view class="menu-list">
        <view
          v-for="item in allMenuItems"
          :key="item.id"
          class="menu-item"
          @click="handleMenuClick(item)"
        >
          <view class="item-left">
            <view class="item-icon" :style="{ backgroundColor: `${item.color}20` }">
              <uni-icons
                v-if="item.iconType === 'uni'"
                :type="item.icon"
                size="18"
                :color="item.color"
              />
              <wd-icon
                v-else-if="item.iconType === 'wd'"
                :name="item.icon"
                size="18px"
                :color="item.color"
              />
            </view>
            <text class="item-title">
              {{ item.title }}
            </text>
          </view>
          <uni-icons type="right" size="16" color="#ccc" />
        </view>
      </view>
    </view>
  </view>

  <!-- 密码输入弹窗 -->
  <view v-if="showPasswordModal" class="password-modal-overlay" @click="handlePasswordCancel">
    <view class="password-modal" @click.stop>
      <view class="modal-header">
        <text class="modal-title">
          验证密码
        </text>
      </view>
      <view class="modal-content">
        <text class="modal-desc">
          请输入您的登录密码以确认注销
        </text>
        <input
          v-model="passwordInput"
          class="password-input"
          password
          placeholder="请输入密码"
          :focus="showPasswordModal"
          @confirm="handlePasswordConfirm"
        >
      </view>
      <view class="modal-footer">
        <button class="cancel-btn" @click="handlePasswordCancel">
          取消
        </button>
        <button class="confirm-btn" @click="handlePasswordConfirm">
          确认
        </button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.my-container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

/* 加载状态 */
.loading-container {
  padding: 50px 20px;
  text-align: center;
}

/* 用户信息 */
.user-info {
  padding: 25px 20px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 0 0 20px 20px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);

  .user-profile {
    display: flex;
    align-items: center;
    position: relative;
    margin-bottom: 20px;

    .user-avatar {
      width: 70px;
      height: 70px;
      border-radius: 50%;
      margin-right: 15px;
      border: 3px solid rgba(255, 255, 255, 0.3);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    .user-details {
      flex: 1;

      .user-name {
        display: block;
        font-size: 18px;
        font-weight: bold;
        color: #fff;
        margin-bottom: 6px;
      }

      .user-level {
        display: inline-block;
        font-size: 13px;
        color: #fff;
        background-color: rgba(0, 0, 0, 0.2);
        padding: 3px 10px;
        border-radius: 12px;
      }
    }

    .refresh-btn {
      padding: 8px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.2);
      transition: all 0.3s ease;

      &:active {
        background-color: rgba(255, 255, 255, 0.3);
        transform: scale(0.95);
      }
    }
  }

  .user-stats {
    .stats-grid {
      display: flex;
      justify-content: space-between;
      background-color: rgba(255, 255, 255, 0.1);
      border-radius: 15px;
      padding: 15px 10px;
      backdrop-filter: blur(10px);

      .stat-item {
        flex: 1;
        text-align: center;

        .stat-value {
          display: block;
          font-size: 20px;
          font-weight: bold;
          color: #fff;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
  }
}

/* 统一菜单列表 */
.menu-section {
  background-color: #fff;
  border-radius: 16px;
  margin: 15px;
  padding: 8px 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  .menu-list {
    .menu-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 18px 0;
      border-bottom: 1px solid #f5f5f5;
      transition: background-color 0.2s ease;

      &:last-child {
        border-bottom: none;
      }

      &:active {
        background-color: #f8f9fa;
        border-radius: 8px;
        margin: 0 -8px;
        padding: 18px 8px;
      }

      .item-left {
        display: flex;
        align-items: center;

        .item-icon {
          width: 36px;
          height: 36px;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
        }

        .item-title {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }
      }
    }
  }
}

/* 我的书架 */
.my-books {
  background-color: #fff;
  border-radius: 12px;
  margin: 0 15px 15px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .view-all {
      font-size: 12px;
      color: #999;
    }
  }

  .books-scroll {
    white-space: nowrap;

    .book-item {
      display: inline-block;
      width: 100px;
      margin-right: 15px;

      .book-cover {
        width: 100px;
        height: 140px;
        border-radius: 8px;
        margin-bottom: 8px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }

      .book-title {
        display: block;
        font-size: 14px;
        color: #333;
        margin-bottom: 6px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .progress-bar {
        width: 100%;
        height: 4px;
        background-color: #eee;
        border-radius: 2px;
        overflow: hidden;

        .progress-fill {
          height: 100%;
          background-color: #4a90e2;
          border-radius: 2px;
        }
      }
    }
  }
}

/* 密码输入弹窗样式 */
.password-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.password-modal {
  background-color: #fff;
  border-radius: 12px;
  width: 300px;
  max-width: 90%;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 20px 20px 10px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.modal-content {
  padding: 20px;
}

.modal-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.4;
}

.password-input {
  width: 100%;
  height: 44px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 0 12px;
  font-size: 16px;
  background-color: #f9f9f9;
  box-sizing: border-box;
}

.password-input:focus {
  border-color: #4a90e2;
  background-color: #fff;
  outline: none;
}

.modal-footer {
  display: flex;
  border-top: 1px solid #f0f0f0;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  height: 50px;
  border: none;
  background-color: transparent;
  font-size: 16px;
  cursor: pointer;
}

.cancel-btn {
  color: #666;
  border-right: 1px solid #f0f0f0;
}

.cancel-btn:active {
  background-color: #f5f5f5;
}

.confirm-btn {
  color: #4a90e2;
  font-weight: 600;
}

.confirm-btn:active {
  background-color: #f0f8ff;
}
</style>
